import 'dart:math';

import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:material_dialogs/dialogs.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:tracker/common/widget/common.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/log/x_logger.dart';
import '../../../../provider/global_provider.dart';
import '../../../../theme/app_theme.dart';
import '../mixin/record_history_mixin.dart';
import '../model/record_history_list_resp.dart';
import '../widget/simple_waveform_progressbar.dart';

class RecordHistoryPage extends ConsumerStatefulWidget {
  const RecordHistoryPage({super.key});

  @override
  ConsumerState<RecordHistoryPage> createState() => _RecordHistoryPageState();
}

class _RecordHistoryPageState extends ConsumerState<RecordHistoryPage>
    with RecordHistoryMixin, WidgetsBindingObserver {
  @override
  void dispose() {

    refreshController.dispose();
    durationSubscription?.cancel();
    playerCompleteSubscription?.cancel();
    super.dispose();
  }
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getDeviceInfo();
      _fetchHistoryList(true);
      initStream();
      final deviceInfo = ref.watch(deviceInfoProvider);

      DateTime now = DateTime.now();
      int currentYear = now.year;
      int currentMonth = now.month;

      // 获取前一个月的年月
      DateTime previousMonth = DateTime(now.year, now.month - 1);
      // 获取前两个月的年月
      DateTime twoMonthsAgo = DateTime(now.year, now.month - 2);

      ToastUtils.showLoading(status: "获取数据...");
      getDayData(deviceInfo.imei ?? "", currentYear.toString(), currentMonth.toString(), dataCallBack: (List<DateTime> dataArr) {
        trackCalendar = dataArr;
          getDayData(deviceInfo.imei ?? "", previousMonth.year.toString(), previousMonth.month.toString(), dataCallBack: (List<DateTime> dataArr) {
            trackCalendar.addAll(dataArr);
              getDayData(deviceInfo.imei ?? "", twoMonthsAgo.year.toString(), twoMonthsAgo.month.toString(), dataCallBack: (List<DateTime> dataArr) {
                trackCalendar.addAll(dataArr);
                  XLogger.info(trackCalendar);
                ToastUtils.dismissLoading();
              },
              );
            },
          );
        },
      );
    });

    super.initState();
    WidgetsBinding.instance.addObserver(this);

    refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      getDeviceInfo();
      XLogger.info("didChangeAppLifecycleState");
    }
  }


  void initStream() {
    durationSubscription = audioPlayer.onPositionChanged.listen(
      (p) {
        historyList[curPLayIndex].progress =
            p.inSeconds / (historyList[curPLayIndex].duration ?? 1);
        setState(() {});
      },
    );
    playerCompleteSubscription =
        audioPlayer.onPlayerComplete.listen((event) async {
      if (historyList[curPLayIndex].status == 0) {
        final res = await readRecordFile(historyList[curPLayIndex]);
        if (res.data != null) {
          historyList[curPLayIndex].status = 1;
        }
      }
      if(isAutoPlay){
        if(curPLayIndex < historyList.length - 1){
          playRecord(historyList[curPLayIndex + 1], curPLayIndex + 1);
        } else {
          setState(() {
            curPLayIndex = -1;
          });
        }
      } else {
        setState(() {
          curPLayIndex = -1;
        });
      }
    });
  }

  _fetchHistoryList(bool isRefresh) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    if (deviceInfo.imei == null || deviceInfo.expired == true) {
      setState(() {
        showLoading = false;
        pageNum = 1;
        historyList = <RecordHistoryData>[];
      });
      refreshController.finishRefresh();
      return;
    }
    final queryParams = {
      'pageNum': pageNum,
      'pageSize': 9999,
      "imei": deviceInfo.imei,
      "dateTime": DateUtil.formatDate(selectTime, format: "yyyy-MM-dd")
    };
    final res = await get<RecordHistoryListResp, RecordHistoryListResp>(
        '$newBaseULr/deviceFile/list',
        queryParameters: queryParams,
        decodeType: RecordHistoryListResp());
    setState(() {
      showLoading = false;
    });
    res.when(success: (resp) {
      if (resp.code == 200) {
        XLogger.info(isRefresh);

        if (isRefresh) {
          historyList = resp.rows!;
          refreshController.finishRefresh();
          pageNum++;

        } else {
          // 判断是否还有数据
          // if (resp.rows!.isEmpty) {
          XLogger.info((resp.total ?? 0));
          XLogger.info(pageNum * 10);

          refreshController.finishLoad(IndicatorResult.noMore);
          return;
          if ((resp.total ?? 0) < (pageNum - 1) * 10) {
            refreshController.finishLoad(IndicatorResult.noMore);
            return;
          } else {
            // pageNum++;
            // historyList.addAll(resp.rows!);
            // refreshController.finishLoad();
          }
        }
        setState(() {});
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取安防列表失败 code: $code msg: $msg');
    });
  }

  _showLoading() {
    if (showLoading) {
      return Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(
          color: AppTheme.themeConfig.primaryColor,
        ),
      );
    } else {
      return _buildListView();
    }
  }
  _routeToVipService(String chooseTabIndex) {
    context.push('${RouterManager.vipService}?chooseTabIndex=${chooseTabIndex}').then((value){
       getDeviceInfo();
    });
  }

  _kaitonggaoqing() {
    /// 自定义一个弹窗
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {

        return Dialog(
          child: Container(
            height: 200,
            width: 300,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: AppTheme.themeConfig.greyBgColor
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 1),
                const Text(
                    '您还未开通高清录音模式',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 10),
                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.primaryColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      _routeToVipService("1");
                      Navigator.of(context).pop();
                    },
                    child: const Text('前往开通'),
                  ),
                ),

                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.infoTextColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('取消'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  _winxintishi() {
    /// 自定义一个弹窗
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {

        return Dialog(
          child: Container(
            height: 340,
            width: 300,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                color: AppTheme.themeConfig.greyBgColor
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const SizedBox(height: 20),
                Text(
                  '温馨提示，免责声明',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                const SizedBox(height: 20),
                const Padding(padding: EdgeInsets.only(left: 20,right: 20, bottom: 0),
                  child: const Text(
                    '   内容不可以传播，不可以用于违法行为。如非法使用导致任何的法律责任均由使用者承担责任，请用户谨慎使用。',
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
                const Padding(padding: EdgeInsets.only(left: 20,right: 20,top: 0),
                  child: const Text(
                    '   安防拾音功能适用于儿童，老人关爱监护及车辆等贵重物品的防丢防盗措施，用户自愿启动安防拾音功能包括自愿购买增值服务项目。',
                    style: TextStyle(
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                      color: Color(0xffE50012),

                    ),
                  ),
                ),
                const SizedBox(height: 30),

                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.primaryColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      String cmd = deviceDetails?.securityStatus == 1 ? "db,0" : "db,1";
                      changeStatus(cmd, change: (){
                        final deviceInfo = ref.watch(deviceInfoProvider);
                        final data = {
                          "imei": deviceInfo.imei,
                          "securityStatus": deviceDetails?.securityStatus == 1 ? "0" : "1"
                        };
                        setDevice(data: data);
                        context.pop();
                      });
                    },
                    child: const Text('同意，我已知晓风险'),
                  ),
                ),
                const SizedBox(height: 10),

                SizedBox(
                  width: 220, // 设置按钮宽度
                  height: 40, // 设置按钮高度
                  child: TextButton(
                    style: TextButton.styleFrom(
                      minimumSize: const Size(100, 40),
                      backgroundColor: AppTheme.themeConfig.infoTextColor, // 设置背景色为蓝色
                      foregroundColor: Colors.white, // 设置文字颜色为白色，增强对比度
                      textStyle: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: const Text('暂不开启'),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  _checkvoice() {
    if (deviceDetails?.securityStatus != 1) { // 如果是关闭状态

      if (deviceDetails?.securityVip == 1) { // 如果是已经购买
        if (deviceDetails?.securityNum == 0 && deviceDetails?.securityDay == 0) {
          _routeToVipService("0");
          return ;
        }
      }else if (isHigh == true && deviceDetails?.highVip != 1){
        _kaitonggaoqing();
        return;
      }else if (deviceDetails?.securityVip == 0) { //如果是未购买
        _routeToVipService("0");
        return ;
      }
      _winxintishi();
    }else {
      String cmd = deviceDetails?.securityStatus == 1 ? "db,0" : "db,1";
      changeStatus(cmd, change: (){
        final deviceInfo = ref.watch(deviceInfoProvider);
        final data = {
          "imei": deviceInfo.imei,
          "securityStatus": deviceDetails?.securityStatus == 1 ? "0" : "1"
        };
        setDevice(data: data);
      });
    }

  }

  _buildListView() {
    return EasyRefresh(
        controller: refreshController,
        onRefresh: () async {
          pageNum = 1;
          _fetchHistoryList(true);
        },
        onLoad: () async {
          _fetchHistoryList(false);
        },
        child: Stack(
          children: [
            _listBuilder(),
            Offstage(
              offstage: historyList.isNotEmpty,
              child: Container(
                alignment: Alignment.center,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.music_note, size: 80, color: AppTheme.themeConfig.infoTextColor.withOpacity(0.3)),
                    const SizedBox(height: 16),
                    Text(
                      '暂无录音记录',
                      style: TextStyle(
                        fontSize: 16,
                        color: AppTheme.themeConfig.infoTextColor,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ));
  }

  _listBuilder() {
    return GridView.builder(
        controller: _scrollController,
        padding: const EdgeInsets.all(12),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          crossAxisSpacing: 8,
          mainAxisSpacing: 8,
          childAspectRatio: 1.8,
        ),
        itemCount: historyList.length,
        itemBuilder: (context, index) {
          RecordHistoryData recordHistoryData = historyList[index];
          final dateStr = DateUtil.formatDate(recordHistoryData.createTime!,
              format: 'MM-dd HH:mm');
          final isPlaying = curPLayIndex == index;
          
          return GestureDetector(
            onTap: () {
              if (deleteMode) {
                recordHistoryData.selected = !recordHistoryData.selected;
                setState(() {});
              } else {
                playRecord(recordHistoryData, index);
                setState(() {});
              }
            },
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: isPlaying
                      ? [
                          AppTheme.themeConfig.primaryColor.withOpacity(0.9),
                          AppTheme.themeConfig.primaryColor,
                        ]
                      : recordHistoryData.status == 1
                          ? [Colors.white, Colors.grey.shade50]
                          : [
                              AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                              Colors.white,
                            ],
                ),
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: isPlaying 
                        ? AppTheme.themeConfig.primaryColor.withOpacity(0.25)
                        : Colors.black.withOpacity(0.06),
                    blurRadius: 8,
                    offset: const Offset(0, 3),
                  ),
                ],
                border: Border.all(
                  color: recordHistoryData.selected
                      ? AppTheme.themeConfig.primaryColor
                      : Colors.transparent,
                  width: 2,
                ),
              ),
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                child: Row(
                  children: [
                    // 左侧播放按钮
                    Container(
                      width: 44,
                      height: 44,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: isPlaying
                            ? Colors.white.withOpacity(0.2)
                            : AppTheme.themeConfig.primaryColor.withOpacity(0.08),
                      ),
                      child: Icon(
                        isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled,
                        size: 28,
                        color: isPlaying
                            ? Colors.white
                            : AppTheme.themeConfig.primaryColor,
                      ),
                    ),
                    
                    const SizedBox(width: 10),
                    
                    // 右侧信息区域
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          // 时间和状态
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  dateStr,
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: isPlaying
                                        ? Colors.white
                                        : AppTheme.themeConfig.primaryTextColor,
                                    fontWeight: FontWeight.w600,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                              const SizedBox(width: 4),
                              if (recordHistoryData.status != 1 && !deleteMode)
                                Container(
                                  width: 6,
                                  height: 6,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Colors.red,
                                    boxShadow: [
                                      BoxShadow(
                                        color: Colors.red.withOpacity(0.5),
                                        blurRadius: 3,
                                        spreadRadius: 1,
                                      ),
                                    ],
                                  ),
                                ),
                              if (deleteMode)
                                Image.asset(
                                  recordHistoryData.selected
                                      ? "assets/images/record_history/icon_checked.png"
                                      : "assets/images/record_history/icon_not_check.png",
                                  width: 18,
                                  height: 18,
                                ),
                            ],
                          ),
                          
                          const SizedBox(height: 4),
                          
                          // 时长
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                            decoration: BoxDecoration(
                              color: isPlaying
                                  ? Colors.white.withOpacity(0.3)
                                  : AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(6),
                            ),
                            child: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(
                                  Icons.access_time,
                                  size: 10,
                                  color: isPlaying ? Colors.white : AppTheme.themeConfig.primaryColor,
                                ),
                                const SizedBox(width: 3),
                                Text(
                                  formatDuration(recordHistoryData.duration ?? 0),
                                  style: TextStyle(
                                    fontSize: 10,
                                    fontWeight: FontWeight.w600,
                                    color: isPlaying ? Colors.white : AppTheme.themeConfig.primaryColor,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          
                          const SizedBox(height: 4),
                          
                          // 进度条
                          if (isPlaying || recordHistoryData.progress > 0)
                            ClipRRect(
                              borderRadius: BorderRadius.circular(2),
                              child: LinearProgressIndicator(
                                value: recordHistoryData.progress,
                                backgroundColor: isPlaying
                                    ? Colors.white.withOpacity(0.3)
                                    : Colors.grey.shade200,
                                valueColor: AlwaysStoppedAnimation<Color>(
                                  isPlaying ? Colors.white : AppTheme.themeConfig.primaryColor,
                                ),
                                minHeight: 2,
                              ),
                            ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
        appBar: AppBar(
          title: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(10),
                ),
                child: const Icon(Icons.headset_mic, color: Colors.white, size: 20),
              ),
              const SizedBox(width: 10),
              const Text('安防录音', style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w700)),
            ],
          ),
          centerTitle: true,
          backgroundColor: AppTheme.themeConfig.primaryColor,
          elevation: 0,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white, size: 20),
            onPressed: () => Navigator.pop(context),
          ),
          actions: [
            IconButton(
              icon: Container(
                padding: const EdgeInsets.all(6),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Icon(Icons.vertical_align_bottom, color: Colors.white, size: 18),
              ),
              onPressed: () {
                _scrollController.animateTo(
                  _scrollController.position.maxScrollExtent, 
                  duration: const Duration(milliseconds: 300), 
                  curve: Curves.easeInOut
                );
              },
            ),
            IconButton(
              icon: Container(
                padding: const EdgeInsets.all(6),
                decoration: BoxDecoration(
                  color: deleteMode ? Colors.white : Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(
                  Icons.delete_outline, 
                  color: deleteMode ? AppTheme.themeConfig.primaryColor : Colors.white, 
                  size: 18
                ),
              ),
              onPressed: () {
                setState(() {
                  if (deleteMode) {
                    return;
                  }
                  deleteMode = !deleteMode;
                  if (deleteMode) {
                    isAllSelect = false;
                  }
                });
              },
            ),
            const SizedBox(width: 8),
          ],
        ),
        backgroundColor: Colors.grey.shade100,
        body: Column(
          children: [
            buildHeader(),
            Expanded(child: _showLoading()),
            _buildBottom()
          ],
        ));
  }

  Widget _buildBottom() {
    return Container(
    // return SafeArea(
    //     top: false,
        child: deleteMode ? buildDeleteBottom() : buildNormalBottom());
  }

  Widget buildNormalBottom() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.only(
          topRight: Radius.circular(30), 
          topLeft: Radius.circular(30)
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, -5),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 顶部功能按钮组
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              _buildControlChip(
                icon: isHigh ? Icons.hd : Icons.hd_outlined,
                label: "高清录音",
                isActive: isHigh,
                onTap: () async {
                  if (deviceDetails?.highVip == 1) {
                  } else {
                    if (isHigh == false) {
                      _kaitonggaoqing();
                      return;
                    }
                  }
                  String cmd = isHigh ? "gq,0" : "gq,1";
                  changeStatus(cmd, change: (){
                    final deviceInfo = ref.watch(deviceInfoProvider);
                    final data = {
                      "imei": deviceInfo.imei,
                      "highStatus": isHigh ? "0" : "1"
                    };
                    setDevice(data: data, voidCallback: (){
                      setState(() {
                        isHigh = !isHigh;
                      });
                    });
                  });
                },
              ),
              _buildControlChip(
                icon: Icons.tune,
                label: "灵敏度",
                onTap: showBottomDialog,
              ),
              _buildControlChip(
                icon: isAutoPlay ? Icons.playlist_play : Icons.playlist_play_outlined,
                label: "自动播放",
                isActive: isAutoPlay,
                onTap: () {
                  setState(() {
                    isAutoPlay = !isAutoPlay;
                  });
                },
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          // 主按钮
          GestureDetector(
            onTap: _checkvoice,
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 16),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: deviceDetails?.securityStatus == 1
                      ? [Colors.red.shade400, Colors.red.shade600]
                      : [
                          AppTheme.themeConfig.primaryColor,
                          AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                        ],
                ),
                borderRadius: BorderRadius.circular(30),
                boxShadow: [
                  BoxShadow(
                    color: (deviceDetails?.securityStatus == 1
                            ? Colors.red
                            : AppTheme.themeConfig.primaryColor)
                        .withOpacity(0.4),
                    blurRadius: 12,
                    offset: const Offset(0, 6),
                  ),
                ],
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    deviceDetails?.securityStatus == 1 
                        ? Icons.stop_circle 
                        : Icons.fiber_manual_record,
                    color: Colors.white,
                    size: 24,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    deviceDetails?.securityStatus == 1 ? "停止录音" : "开始录音",
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.w700,
                      letterSpacing: 1,
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          const SizedBox(height: 12),
          
          // 温馨提示
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.orange.shade50,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.orange.shade200, width: 1),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(Icons.info_outline, 
                  size: 16, 
                  color: Colors.orange.shade700
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: Text(
                    "录音功能适用于安全监护，禁止用于违法行为。使用者需承担相关法律责任。",
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.orange.shade900,
                      height: 1.4,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  Widget _buildControlChip({
    required IconData icon,
    required String label,
    bool isActive = false,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
        decoration: BoxDecoration(
          gradient: isActive
              ? LinearGradient(
                  colors: [
                    AppTheme.themeConfig.primaryColor,
                    AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                  ],
                )
              : null,
          color: isActive ? null : Colors.grey.shade100,
          borderRadius: BorderRadius.circular(20),
          border: Border.all(
            color: isActive 
                ? AppTheme.themeConfig.primaryColor
                : Colors.grey.shade300,
            width: 1.5,
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              size: 18,
              color: isActive ? Colors.white : AppTheme.themeConfig.secondaryTextColor,
            ),
            const SizedBox(width: 6),
            Text(
              label,
              style: TextStyle(
                fontSize: 13,
                fontWeight: FontWeight.w600,
                color: isActive ? Colors.white : AppTheme.themeConfig.secondaryTextColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void showBottomDialog() {
    Dialogs.bottomMaterialDialog(
        context: context,
        customView: Column(
          children: [
            Stack(
              alignment: Alignment.center,
              children: [
                Container(
                  alignment: Alignment.center,
                  width: MediaQuery.of(context).size.width,
                  padding: const EdgeInsets.only(top: 20, bottom: 16),
                  child: lpText("录音灵敏度设置", size: 20),
                ),
                Positioned(
                  top: 16,
                  right: 16,
                  child: GestureDetector(
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                    child: SizedBox(
                      width: 40,
                      height: 40,
                      child: lpText('取消',
                          size: 14, color: AppTheme.themeConfig.primaryColor),
                    ),
                  ),
                )
              ],
            ),
            StatefulBuilder(builder: (context, setState) {
              return Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  children: [
                    lpText("低"),
                    Expanded(
                        child: Slider(
                          activeColor: AppTheme.themeConfig.primaryColor,
                          value: sliderProgress,
                          max: 1,
                          divisions: 2,
                          onChanged: (double value) {
                            // String cmd = "dbcs,${value == 0.0 ? 100 : (value == 1.0 ? 50 : 80)},${value == 0.0 ? 5 : (value == 1.0 ? 1 : 2)}";
                            // changeStatus(cmd, change: (){
                            //   final deviceInfo = ref.watch(deviceInfoProvider);
                            //   final data = {
                            //     "imei": deviceInfo.imei,
                            //     "recordGears": value == 1.0 ? "1" : (value == 0.5 ? "2" : "5")
                            //   };
                            //   XLogger.info(cmd);
                            //
                            //   setDevice(data: data, voidCallback: (){
                            //     setState(() {
                            //       sliderProgress = value;
                            //     });
                            //   });
                            // });
                          },
                          onChangeEnd: (double value) {
                            String cmd = "dbcs,${value == 0.0 ? 100 : (value == 1.0 ? 10 : 50)},1";

                            // String cmd = "dbcs,${value == 0.0 ? 100 : (value == 1.0 ? 50 : 80)},${value == 0.0 ? 5 : (value == 1.0 ? 1 : 2)}";
                            changeStatus(cmd, change: (){
                              final deviceInfo = ref.watch(deviceInfoProvider);
                              final data = {
                                "imei": deviceInfo.imei,
                                "recordGears": value == 1.0 ? "1" : (value == 0.5 ? "2" : "5")
                              };
                              XLogger.info(cmd);

                              setDevice(data: data, voidCallback: (){
                                setState(() {
                                  sliderProgress = value;
                                });
                              });
                            });
                          },
                        )),
                    lpText("高")
                  ],
                ),
              );
            })
          ],
        ));
  }

  Widget buildDeleteBottom() {
    final selectedCount = historyList.where((element) => element.selected).length;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.only(
          topRight: Radius.circular(30),
          topLeft: Radius.circular(30),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: const Offset(0, -5),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 顶部选择状态栏
          Row(
            children: [
              GestureDetector(
                onTap: selectAll,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
                  decoration: BoxDecoration(
                    color: isAllSelect 
                        ? AppTheme.themeConfig.primaryColor.withOpacity(0.1)
                        : Colors.grey.shade100,
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(
                      color: isAllSelect 
                          ? AppTheme.themeConfig.primaryColor
                          : Colors.grey.shade300,
                    ),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(
                        isAllSelect ? Icons.check_circle : Icons.radio_button_unchecked,
                        size: 20,
                        color: isAllSelect 
                            ? AppTheme.themeConfig.primaryColor
                            : AppTheme.themeConfig.secondaryTextColor,
                      ),
                      const SizedBox(width: 6),
                      Text(
                        "全选",
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: isAllSelect 
                              ? AppTheme.themeConfig.primaryColor
                              : AppTheme.themeConfig.secondaryTextColor,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
                  decoration: BoxDecoration(
                    color: selectedCount > 0 
                        ? AppTheme.themeConfig.primaryColor.withOpacity(0.1)
                        : Colors.grey.shade50,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Text(
                    selectedCount > 0 
                        ? "已选择 $selectedCount 条录音"
                        : "请选择要删除的录音",
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: selectedCount > 0
                          ? AppTheme.themeConfig.primaryColor
                          : AppTheme.themeConfig.infoTextColor,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
            ],
          ),
          
          const SizedBox(height: 16),
          
          // 底部按钮组
          Row(
            children: [
              Expanded(
                child: GestureDetector(
                  onTap: cancelDeleteMode,
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(24),
                      color: Colors.grey.shade100,
                      border: Border.all(
                        width: 1.5, 
                        color: Colors.grey.shade300
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(Icons.close, size: 18, color: AppTheme.themeConfig.secondaryTextColor),
                        const SizedBox(width: 6),
                        Text(
                          "取消",
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: AppTheme.themeConfig.secondaryTextColor,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: GestureDetector(
                  onTap: () {
                    List<int?> fileId = historyList
                        .where((e) => e.selected)
                        .map((e) => e.fileId)
                        .toList();
                    if (fileId.isEmpty) {
                      ToastUtils.showToast("请选择一条录音");
                      return;
                    }
                    ToastUtils.showDeleteDialog(context,
                        confirmCallback: deleteRecord);
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(vertical: 14),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(24),
                      gradient: LinearGradient(
                        colors: selectedCount > 0
                            ? [Colors.red.shade400, Colors.red.shade600]
                            : [Colors.grey.shade300, Colors.grey.shade400],
                      ),
                      boxShadow: selectedCount > 0
                          ? [
                              BoxShadow(
                                color: Colors.red.withOpacity(0.3),
                                blurRadius: 8,
                                offset: const Offset(0, 4),
                              ),
                            ]
                          : null,
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Icon(Icons.delete_forever, size: 20, color: Colors.white),
                        const SizedBox(width: 6),
                        const Text(
                          "删除",
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w700,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
  Widget _taocanyuliang() {
    if ((deviceDetails?.securityDay ?? 0) > 0) {
     return lpText("余${deviceDetails?.securityDay ??0}天${deviceDetails?.securityNum ??0}条");

    }else {
     return lpText("余${deviceDetails?.securityNum ??0}条");
    };
  }
  Widget buildHeader() {
    final deviceInfo = ref.watch(deviceInfoProvider);
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.white,
            Colors.grey.shade50,
          ],
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          // 第一行：日期选择
          GestureDetector(
            onTap: showDateSelect,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
                border: Border.all(color: AppTheme.themeConfig.primaryColor.withOpacity(0.3)),
                boxShadow: [
                  BoxShadow(
                    color: AppTheme.themeConfig.primaryColor.withOpacity(0.1),
                    blurRadius: 8,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.calendar_today,
                    size: 16,
                    color: AppTheme.themeConfig.primaryColor,
                  ),
                  const SizedBox(width: 8),
                  Text(
                    DateUtil.formatDate(selectTime, format: "yyyy-MM-dd"),
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: AppTheme.themeConfig.primaryTextColor,
                    ),
                  ),
                  const SizedBox(width: 4),
                  Icon(
                    Icons.keyboard_arrow_down,
                    size: 18,
                    color: AppTheme.themeConfig.secondaryTextColor,
                  ),
                ],
              ),
            ),
          ),
          
          const SizedBox(height: 10),
          
          // 第二行：套餐余量和购买按钮
          Row(
            children: [
              // 套餐余量
              Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: Colors.orange.shade50,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: Colors.orange.shade200),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.access_time, size: 14, color: Colors.orange.shade700),
                      const SizedBox(width: 6),
                      Flexible(child: _taocanyuliang()),
                    ],
                  ),
                ),
              ),
              
              const SizedBox(width: 10),
              
              // 购买按钮
              GestureDetector(
                onTap: (){
                  _routeToVipService("0");
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        AppTheme.themeConfig.primaryColor,
                        AppTheme.themeConfig.primaryColor.withOpacity(0.8),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: AppTheme.themeConfig.primaryColor.withOpacity(0.3),
                        blurRadius: 8,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const Icon(Icons.add_shopping_cart, size: 16, color: Colors.white),
                      const SizedBox(width: 6),
                      lpText("购买条数", color: Colors.white, size: 13),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
  Widget? _dayBuilder({
    required date,
    textStyle,
    decoration,
    isSelected,
    isDisabled,
    isToday,
  }) {
    Widget? dayWidget;

    // 如果小于用户最小日期，则将文字颜色设置为灰色

    if (date.isBefore(DateTime.now().subtract(const Duration(days: 60)))) {
      textStyle = textStyle.copyWith(color: AppTheme.themeConfig.infoTextColor);
    } else {
      textStyle =
          textStyle.copyWith(color: AppTheme.themeConfig.primaryTextColor);
    }

    // 只处理trackCalendar中的日期
    if (trackCalendar.isEmpty || !trackCalendar.contains(date)) {
      dayWidget = Container(
        decoration: decoration,
        alignment: Alignment.center,
        child: Text(
          MaterialLocalizations.of(context).formatDecimal(date.day),
          style: textStyle,
        ),
      );
      return dayWidget;
    }
    dayWidget = Container(
      decoration: decoration,
      alignment: Alignment.center,
      child: Center(
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Text(
              MaterialLocalizations.of(context).formatDecimal(date.day),
              style: textStyle,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 27.5),
              child: Container(
                height: 4,
                width: 4,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: isSelected == true ? Colors.white : Colors.red[500],
                ),
              ),
            ),
          ],
        ),
      ),
    );

    return dayWidget;
  }
  void showDateSelect() {
    final BuildContext dialogContext = context; // 保存有效的 context

    if (!isRefreshTrackCalendar) {
      // await loadTrackCalendarData();
    }
    var config = CalendarDatePicker2WithActionButtonsConfig(
      // 不能选择今天之后的日期
      lastDate: DateTime.now(),
      // 只能选择最近60天的日期
      firstDate:DateTime.now().subtract(Duration(days: 60)),
      dayBuilder: _dayBuilder,
    );
    showDialog(context: dialogContext, builder: (context) {
      return Dialog(
        insetPadding: const EdgeInsets.symmetric(
            horizontal: 16.0, vertical: 24.0),
        backgroundColor: Theme.of(context).canvasColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
        clipBehavior: Clip.antiAlias,
        child: SizedBox(
          width: 325,
          height: max(400, 410),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CalendarDatePicker2WithActionButtons(
                value: calendarValue,
                config: config.copyWith(openedFromDialog: false),
                onValueChanged: (value) {
                  XLogger.info(value);
                  if (value.isNotEmpty) {
                    DateTime chooseDate = value[0]!;
                    XLogger.info(chooseDate);
                    if (chooseDate != null) {
                      DateTime startTime = DateTime.now().subtract(const Duration(days: 15));
                      String content = "超出可查询天数，请购买录音恢复套餐";
                      if(deviceDetails?.playbackVip == 1){
                        startTime = DateTime.now().subtract(const Duration(days: 60));
                        content = "超出最大可查询天数";
                      }
                      if(chooseDate.isBefore(startTime)){
                        XLogger.info("去支付买恢复套餐");
                        XLogger.info(context);

                        ToastUtils.showCheckDateDialog(context, content: content, confirmCallback: (){
                          // if(deviceDetails?.playbackVip != 1){
                          // context.push('${RouterManager.vipService}?chooseTabIndex=2');
                          // }
                          _routeToVipService("2");
                        });

                      }else {
                        selectTime = chooseDate;
                        pageNum = 1;
                        _fetchHistoryList(true);
                        setState(() {
                          calendarValue = value;
                        });
                        Navigator.pop(context);
                      }
                    }else {

                    }
                  }
                },
                onOkTapped: () {
                  XLogger.info("onOkTapped");
                },
                onCancelTapped: () {
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      );
    });


  }
}
